<?php

namespace mpend\modules\dynamic\models;

use Yii;
use yii\data\ActiveDataProvider;

/**
 * This is the model class for table "{{%dynamic}}".
 *
 * @property int $id
 * @property string $user_id 用户ID
 * @property string $content
 * @property int $direction 动态类型：0主动动态，1被动动态
 * @property int $retweet_id 转发动态原始ID
 * @property int $status
 * @property string $created_at
 * @property string $updated_at
 * @property string $deleted_at
 */
class DynamicVideoSearch extends \common\logics\DynamicLogic {

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params = []) {
        $query = static::find()->where([
            'status' => static::STATUS_ACTIVE,
            'deleted_at' => 0,
            'format' => parent::FORMAT_VIDEO
        ]);
        $query->with(['user', 'stats', 'dynamicVideo']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        Yii::$app->db->cache(function ($db) use ($dataProvider) {
            $dataProvider->prepare();
        }, 60);

        return $dataProvider;
    }

    public function getPublishTime() {
        return $this->created_at;
    }

    public function fields() {
        return [
            'id',
            'format',
            'text' => 'content',
            'video' => function($model){
                $video = $model->video;

                if(!$video){
                    return null;
                }

                $params = Yii::$app->params['alioss_video_host'];

                $videoUrl = $params['host'] . '/' . $video['filename'];
                $video['video_url'] = $videoUrl;
                $video['cover_url'] =
                    $videoUrl
                    . '?'
                    . 'x-oss-process=video/snapshot,'
                    . 't_' . $params['t'] . ','
                    . 'w_' . $params['width'] . ','
                    . 'h_' . $params['height'] . ','
                    . 'f_' . $params['format'] . ','
                    . 'm_' . $params['module'];

                return $video;
            },
            'time' => 'publishTime',
            'tools',
            'liked',
            'collected',
            'user',
            'redirect',
            'retweet',
        ];
    }

}
